<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @package 		PyroCMS
 * @subpackage 		reg_stat module
 * @author		Alireza Youhan (pyrocms.ir@gmail.com)
 *
 * Shows registration statistics of the site
 */

class Widget_reg_stats extends Widgets {

    public $title = array(
        'en' => 'Registration Statistics'
    );
    public $description = array(
        'en' => 'Shows registration statistics of the site'
    );
    public $author = 'Alireza Youhan';
    public $website = 'http://pyrocms.ir';
    public $version = '1.0';
    public $fields = array(
        array(
            'field' => 'limit',
            'label' => 'Number of posts',
        )
    );
    
    public function form($options)
    {
            !empty($options['limit']) OR $options['limit'] = 30;

            return array(
                'options' => $options
            );
    }

    public function run($options) {
        
        
        // sets default number of posts to be shown
        empty($options['limit']) AND $options['limit'] = 5;
        
        // Not FALSE? Return it
        if ($cached_response = $this->pyrocache->get('reg_stats'))
        {
                $data['stats_regs'] = $cached_response['stats_regs'];
                $data['stats_actives'] = $cached_response['stats_actives'];
        }

        else
        {
                try
                {

                    //get regs 
                    $query2 = "SELECT DATE_FORMAT( FROM_UNIXTIME(created_on),'%Y-%m-%e') AS date_field, COUNT( * ) AS count
                    FROM default_users
                    WHERE created_on <= ".time()."
                    AND created_on >= UNIX_TIMESTAMP( DATE_SUB(NOW(), INTERVAL ".$options['limit']." DAY) )
                    GROUP BY date_field ORDER BY created_on DESC";
                    $q2 = $this->db->query($query2)->result();

                    $startdate = time();
                    $days = $options['limit'];

                    foreach ($q2 as $counts) { // we convert the results to a usable form
                        $count_info2[$counts->date_field] = $counts->count;
                    }
                    for ($i = 0; $i <= $days; $i++) {
                        $date = date('Y-m-j', $startdate-$i*60*60*24);
                        $regs[strtotime($date)."000"] = array_key_exists($date, $count_info2) ? $count_info2[$date] : 0;
                    }

                    //get actives 
                    $query3 = "SELECT DATE_FORMAT( FROM_UNIXTIME(created_on),'%Y-%m-%e') AS date_field, COUNT( * ) AS count
                    FROM default_users
                    WHERE created_on <= ".time()."
                    AND created_on >= UNIX_TIMESTAMP( DATE_SUB(NOW(), INTERVAL ".$options['limit']." DAY) )
                    AND active = 1
                    GROUP BY date_field ORDER BY created_on DESC";
                    $q3 = $this->db->query($query3)->result();
                    foreach ($q3 as $counts) { // we convert the results to a usable form
                        $count_info3[$counts->date_field] = $counts->count;
                    }
                    for ($i = 0; $i <= $days; $i++) {
                        $date = date('Y-m-j', $startdate-$i*60*60*24);
                        $actives[strtotime($date)."000"] = array_key_exists($date, $count_info3) ? $count_info3[$date] : 0;
                    }


                    /* build tables */
                    if (count($regs))
                    {

                            foreach ($regs as $date => $count)
                            {
                                    $flot_datas_reg[] = '[' . $date . ',' . $count . ']';
                            }
                            foreach ($actives as $date => $count)
                            {
                                    $flot_datas_actives[] = '[' . $date . ',' . $count . ']';
                            }

                            $flot_data_regs = '[' . implode(',', $flot_datas_reg) . ']';
                            $flot_data_actives = '[' . implode(',', $flot_datas_actives) . ']';
                    }


                    $data['stats_regs'] = $flot_data_regs;
                    $data['stats_actives'] = $flot_data_actives;

                    // Call the model or library with the method provided and the same arguments
                    $this->pyrocache->write(array('stats_regs' => $flot_data_regs,'stats_actives' => $flot_data_actives), 'reg_stats', 60 * 60 * 2); // 6 hours
            }

            catch (Exception $e)
            {
                    $data['messages']['notice'] = sprintf('could not gather the statistics', anchor('admin/settings', lang('cp_nav_settings')));
            }
        }
     
        
        
        $return->reg_stats = $data;
        return $return;
    }

}
